package tx.yt.charge.web;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * @author: chenmiao@hupu.com
 * Date: 2015-1-8
 */
@Controller
@RequestMapping(value = "/upload")
public class UploadController {

    @RequestMapping(value = "/demo")
    public String input() {
        return "/upload/uploadDemo";
    }

    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    @ResponseBody
    public String submit(HttpServletRequest req, @RequestParam MultipartFile image) throws IOException {
        String realPath = req.getSession().getServletContext().getRealPath("/upload");
        FileUtils.copyInputStreamToFile(image.getInputStream(), new File(realPath, image.getOriginalFilename()));
        return "File Upload success";
    }

    @RequestMapping(value = "/submits", method = RequestMethod.POST)
    @ResponseBody
    public String submits(HttpServletRequest req, @RequestParam MultipartFile[] images) throws IOException {
        String realPath = req.getSession().getServletContext().getRealPath("/upload");
        for(MultipartFile image : images) {
            FileUtils.copyInputStreamToFile(image.getInputStream(), new File(realPath, image.getOriginalFilename()));
        }
        return "Files upload success";
    }
}
